package org.itzheng.myrxframe.base;

import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import org.itzheng.and.baseutils.log.LogHelper;
import org.itzheng.myrxframe.ui.loading.LoadingPopup;

/**
 * Title:<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2019-4-9.
 */
public class BaseV4Fragment extends Fragment {
    private static final String TAG = "BaseV4Fragment";
    protected View rootView;
    LoadingPopup loadingPopup;

    protected void showLoading() {
        if (loadingPopup == null) {
            loadingPopup = new LoadingPopup(getActivity());
        }
        if (!loadingPopup.isShowing()) {
            View view = getView();
            if (view == null) {

            }
            loadingPopup.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        }
    }

    /**
     * 用于记录是否显示 onFirstVisible
     */
    private byte firstVisible = 0b00;
    /**
     * 只要执行过 onFirstVisible 这个方法就是false
     */
    protected boolean isFirstVisible = true;

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstVisible) {
            //如果已经执行过onFirstVisible 就没必要判断了
            firstVisible = (byte) (firstVisible | 0b10);
            if (firstVisible == 0b11) {
                onFirstVisible();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isFirstVisible) {
            //如果已经执行过onFirstVisible 就没必要判断了
            if (isVisibleToUser) {
                firstVisible = (byte) (firstVisible | 0b01);
                if (firstVisible == 0b11) {
                    onFirstVisible();
                }
            }
        }
    }

    /**
     * 第一次用户可见，即，setUserVisibleHint = true，onResume 两次都只执行一次时
     */
    protected void onFirstVisible() {
        isFirstVisible = false;
        LogHelper.w(TAG, "onFirstVisible: " + firstVisible);
    }

    protected void dismissLoading() {
        if (loadingPopup != null && loadingPopup.isShowing()) {
            loadingPopup.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        dismissLoading();
        loadingPopup = null;
        if (null != rootView) {
            //只是将 rootView 移除，并没有置空，下次还可复用
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }
}
